package com.comsoftstar.nt5s.Activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.hzc.imagepicker.SImagePicker;
import com.hzc.imagepicker.activity.PhotoPickerActivity;
import com.hzc.nt5s.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class NT5SActivity extends AppCompatActivity implements View.OnClickListener {

    public static final int REQUEST_CODE_AVATAR = 100;
    public static final int REQUEST_CODE_IMAGE = 101;

    private Button pickImageBtn;
    private Button searchBtn;
    private Button searchReport;
    private Button quality;
    private Button regulations;
    private ImageView back;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_NT5S);
        initUI();
        android.support.v7.app.ActionBar actionBar=getSupportActionBar();
        if(actionBar != null){
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }
    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish(); // back button
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initUI() {
        pickImageBtn = (Button) findViewById(R.id.pick_image);
        pickImageBtn.setOnClickListener(this);
        searchBtn = (Button) findViewById(R.id.btn_search);
        searchBtn.setOnClickListener(this);
        searchReport = (Button) findViewById(R.id.btn_report);
        searchReport.setOnClickListener(this);
        quality= (Button) findViewById(R.id.btn_quality);
        quality.setOnClickListener(this);
        regulations=(Button) findViewById(R.id.btn_regulations);
        regulations.setOnClickListener(this);
        back=(ImageView)findViewById(R.id.iv_back);
        back.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.pick_image:                                                       //返回
                SImagePicker
                        .from(NT5SActivity.this)
                        .maxCount(9)    //最大选择数
                        .rowCount(3)    //列数
                        .showCamera(true)
                        .pickMode(SImagePicker.MODE_IMAGE)  //1
                        .forResult(REQUEST_CODE_IMAGE);    //101
                break;
            case R.id.btn_search:
                Intent intent = new Intent(NT5SActivity.this, SearchActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_report:
                Intent intent2 = new Intent(NT5SActivity.this, ReportActivity.class);
                startActivity(intent2);
                break;
            case R.id.btn_quality:
                Intent intent3 = new Intent(NT5SActivity.this, QualityActivity.class);
                startActivity(intent3);
                break;
            case R.id.btn_regulations:
                Intent intent4 = new Intent(NT5SActivity.this, RegulationsActivity.class);
                startActivity(intent4);
                break;
            case R.id.iv_back:
                finish();
                break;
        }

    }
    private  ArrayList<String> pathlist2=new ArrayList<>();
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            final ArrayList<String> pathList =
                    data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT_SELECTION);

          //  showimagesize(pathList);
            Toast.makeText(NT5SActivity.this, String.format("Size : %s", String.valueOf(new File(pathList.get(0).toString()).length()/1024)), Toast.LENGTH_LONG).show();
            Toast.makeText(this, pathList.get(0).toString(), Toast.LENGTH_LONG).show();
            try {
                // 获取图片路径
              //  oldFile = FileUtil.getTempFile(this, data.getData());
                // 设置获取图片显示ImageView
              //  ((ImageView) (findViewById(R.id.id_luban_choose_pic_show))).setImageBitmap(BitmapFactory.decodeFile(oldFile.getAbsolutePath()));
                // 设置获取图片大小
              //  ((TextView) (findViewById(R.id.id_luban_choose_pic_size))).setText(String.format("Size : %s", StringUtils.getReadableFileSize(oldFile.length())));
                // 启动Luban进行图片压缩
                pathlist2.clear();
                for (int i = 0; i <pathList.size() ; i++) {


                    Luban.get(NT5SActivity.this)
                            .load(new File(pathList.get(i).toString())) // 要压缩的图片
                            .setCompressListener(new OnCompressListener() {
                                @Override
                                public void onStart() {
                                    // 压缩开始前调用 可以在方法内启动loading UI
                                    Toast.makeText(NT5SActivity.this, "我要开着Luban浪荡了~", Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onSuccess(File newFile) {
                                    // 压缩成功后调用，返回压缩后的图片文件
                                    //copyFile(newFile.toString(), pathList.get(0).toString().replace(".", "-2."));
                                      Toast.makeText(NT5SActivity.this, newFile.toString(), Toast.LENGTH_SHORT).show();
                                        newFile.delete();
                                        pathlist2.add(newFile.toString());
                                    //  Toast.makeText(NT5SActivity.this, String.format("Size : %s", String.valueOf(newFile.length()/1024)), Toast.LENGTH_LONG).show();


                                    // 设置获取图片显示ImageView
                                    //   ((ImageView) (findViewById(R.id.id_luban_compress_end_show))).setImageBitmap(BitmapFactory.decodeFile(newFile.getAbsolutePath()));
                                    // 设置获取图片大小
                                    //   ((TextView) (findViewById(R.id.id_luban_compress_end_size))).setText(String.format("Size : %s", StringUtils.getReadableFileSize(newFile.length())));
                                }
                                @Override
                                public void onError(Throwable e) {
                                    // 压缩过程中出现异常
                                    Toast.makeText(NT5SActivity.this, "丫的，翻车了" + e.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            }).launch(); // 启动压缩
                }
            } catch (Exception e) {
                Toast.makeText(this, "读取图片失败~", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
            /**======================*/
//            RequestParams params = new RequestParams(IConstant.URL + "upload");
//            User user = PreferencesUtil.getUser(NT5SActivity.this);
//            params.addBodyParameter("MdCode", "002011");//操作对象
//            params.addBodyParameter("UserName", user.getUserName());//文件后缀名(带点)
//            List<KeyValue> list = new ArrayList<>();
//            for (int i = 0; i < pathList.size(); i++) {
//                list.add(new KeyValue("image" + i, new File(pathList.get(i))));
//                MultipartBody body = new MultipartBody(list, "UTF-8");
//                params.setRequestBody(body);
//            }
////                System.out.println("请求的URL：" + params.toString());
//                x.http().post(params, new Callback.CommonCallback<String>() {
//                    @Override
//                    public void onSuccess(String result) {
////                        System.out.println("返回结果：" + result);
//                        String results[] = result.split(":");
//                        if (results[0].equals("1")) {
//                            Toast.makeText(NT5SActivity.this, "上传成功", Toast.LENGTH_LONG).show();
//                        }
//                    }
//
//                    @Override
//                    public void onError(Throwable ex, boolean isOnCallback) {
//
//                    }
//
//                    @Override
//                    public void onCancelled(CancelledException cex) {
//
//                    }
//
//                    @Override
//                    public void onFinished() {
//
//                    }
//                });
       }
    }
    private void showimagesize(ArrayList<String> pathList){

    }
    public void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1024];
                int length;
                while ( (byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        }
        catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();

        }

    }
}
